import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pixelyear/bean/DateBean.dart';
import 'package:pixelyear/bean/YearBean.dart';
import 'package:pixelyear/sql/RecordSqlUtils.dart';
import 'package:pixelyear/sql/Sql.dart';
import 'package:pixelyear/utils/SpUtils.dart';
import 'package:pixelyear/utils/constant/AssetsConstant.dart';
import 'package:pixelyear/utils/ImageLoad.dart';
import 'package:pixelyear/utils/Utils.dart';
import 'package:pixelyear/utils/constant/SpKey.dart';
import 'package:pixelyear/utils/constant/YxsColor.dart';
import 'package:pixelyear/widget/PixelView.dart';
import 'package:pixelyear/widget/StateBarFulWidget.dart';
import 'package:pixelyear/utils/extension/ContextUtils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pixelyear/widget/dialog/HomeListDialog.dart';
import 'package:pixelyear/widget/text/PaddingTextWidget.dart';

class HomeUI extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeState();
  }
}

class HomeState extends State<HomeUI> {
  List<YearBean> data = [];
  PageController pageController = PageController();
  String nowChooseYear = '';
  String nowChooseMonth = '';
  int nowMonthIndex = -1;
  RecordSqlUtils recordUtils;
  int currentPageIndex = -1;

  @override
  void initState() {
    super.initState();
    recordUtils = Sql.getRecordUtils();
    init();
  }

  @override
  Widget build(BuildContext context) {
    return StateBarFulWidget(
      stateBarTextColor: false,
      child: Stack(
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTitle(context),
              _buildPageView(context, data),
            ],
          ),
          Positioned(
            right: 15.w,
            bottom: 40.w,
            child: _buildToolsWidget(context),
          ),
        ],
      ),
    );
  }

  init() async {
    nowMonthIndex = -1;

    //计算月份
    int year = Utils.getYear();
    int month = Utils.getMonth();
    int firstYear =
        await SpUtils.getYxsInt(SpKey.FIRST_ENTER_APP_YEAR, def: year);
    //如果年数一样 那就计算月数，如果月数一样就是这个月到年底 如果不一样 就是进入App月份到年底
    int i = (year - firstYear + 1) * 12;
    List<YearBean> _data = [];
    for (int j = 1; j <= i; j++) {
      int _index = j % 12;
      int index = _index == 0 ? 12 : _index;
      int _calcYear = firstYear + j ~/ 12;
      int calcYear =
          (j % 12 == 0 && _calcYear > 0) ? _calcYear - 1 : _calcYear; //计算出来的年份
      if (calcYear == year && index == month) nowMonthIndex = j - 1;
      if (nowMonthIndex == j) {
        var l = await recordUtils.getData(calcYear, index);
        _data.add(YearBean(calcYear, index, l));
      } else
        _data.add(YearBean(calcYear, index, []));
    }

    setState(() {
      nowChooseMonth = month.toString();
      nowChooseYear = year.toString();
      data = _data;
    });

    Utils.timeTask(500, () {
      if (pageController.hasClients) {
        pageController.animateToPage(nowMonthIndex,
            curve: Curves.ease, duration: Duration(milliseconds: 300));
      }
    });
  }

  _onPageChange(int index, YearBean bean) async {
    currentPageIndex = index;
    if (bean.list.isEmpty) {
      var l = await recordUtils.getData(bean.year, bean.month);
      bean.list = l;
      data[index] = bean;
    }
    setState(() {
      nowChooseMonth = bean.month.toString();
      nowChooseYear = bean.year.toString();
    });
  }

  Widget _buildTitle(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(
          top: 10.w + context.stateBarHeight, left: 10.w, bottom: 20.w),
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
                text: "$nowChooseYear年",
                style: TextStyle(
                  fontSize: 18.sp,
                )),
            TextSpan(
                text: "   $nowChooseMonth月",
                style: TextStyle(
                  fontSize: 15.sp,
                )),
          ],
        ),
      ),
    );
  }

  Widget _buildPageView(BuildContext context, List<YearBean> data) {
    return Expanded(
      child: PageView.builder(
        controller: pageController,
        onPageChanged: (index) {
          _onPageChange(index, data[index]);
        },
        itemBuilder: (ctx, index) {
          return _buildPager(context, data[index]);
        },
        itemCount: data.length,
      ),
    );
  }

  //构造右下工具按钮
  Widget _buildToolsWidget(BuildContext context) {
    return Column(
      children: [
        _buildRoundImage(AssetsConstant.up, () {
          setState(() {
            pageController.animateToPage(nowMonthIndex,
                curve: Curves.ease, duration: Duration(milliseconds: 300));
          });
        }),
        _buildRoundImage(AssetsConstant.yearView, () {}),
        _buildRoundImage(AssetsConstant.setting, () {}),
      ],
    );
  }

  //右下角工具圆形控件
  Widget _buildRoundImage(String img, Function click) {
    return GestureDetector(
      onTap: click,
      child: Container(
        height: 45.w,
        width: 45.w,
        margin: EdgeInsets.only(bottom: 25.w),
        padding: EdgeInsets.all(10.w),
        decoration: BoxDecoration(
          color: YxsColor.blackf3f4f5,
          borderRadius: new BorderRadius.circular((30.w)),
        ),
        child: ImageLoad.loadAssets(img, width: 25.w, height: 25.w),
      ),
    );
  }

  //PageView
  Widget _buildPager(context, data) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildWeekView(),
        _buildPixelView(context, data),
        _buildListView(context),
      ],
    );
  }

  Widget _buildWeekView() {
    return Padding(
      padding: EdgeInsets.only(left: 5.w, right: 5.w),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          _buildWeekText('一'),
          _buildWeekText('二'),
          _buildWeekText('三'),
          _buildWeekText('四'),
          _buildWeekText('五'),
          _buildWeekText('六'),
          _buildWeekText('日'),
        ],
      ),
    );
  }

  Widget _buildWeekText(String text) {
    return Expanded(
        flex: 1,
        child: Center(
          child: Text(
            text,
            style: TextStyle(fontSize: 18.sp, color: YxsColor.black666),
          ),
        ));
  }

  Widget _buildPixelView(context, data) {
    return Container(
      margin: EdgeInsets.only(top: 10.w),
      child: PixelView.builder(
        context,
        data,
        (int year, int month, int day) {
          showClickDialog(context, year, month, day);
        },
      ),
    );
  }

  //构造底部日记列表
  Widget _buildListView(BuildContext context) {
    return Expanded(
      child: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          child: Padding(
            padding: EdgeInsets.only(top: 10.w),
            child: ListView.builder(
              itemBuilder: (ctx, index) {
                return _buildListItem(
                    context,
                    index,
                    data[currentPageIndex].list[index],
                    data[currentPageIndex].list.length);
              },
              itemCount: (currentPageIndex == -1)
                  ? 0
                  : data[currentPageIndex].list.length,
            ),
          )),
    );
  }

  //构造日记列表的Item
  Widget _buildListItem(
      BuildContext context, int index, DateBean bean, int length) {
    return Padding(
      padding: EdgeInsets.only(left: 10.w),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                height: 2.w,
                margin: EdgeInsets.only(bottom: 2.w),
                child: VerticalDivider(
                    width: 1.w,
                    color: index > 1 ? YxsColor.blue2595e4 : Colors.white,
                    thickness: 1.w),
              ),
              Container(
                width: 12.w,
                height: 12.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(28.w)),
                  border: Border.all(
                      color: YxsColor.blue2595e4,
                      width: 1.w,
                      style: BorderStyle.solid),
                ),
              ),
              Container(
                height: 38.w,
                margin: EdgeInsets.only(top: 2.w),
                child: VerticalDivider(
                    width: 1.w,
                    color: (index != length - 1)
                        ? YxsColor.blue2595e4
                        : Colors.white,
                    thickness: 1.w),
              ),
            ],
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              PaddingTextWidget(
                '${bean.day} 号',
                padding: EdgeInsets.only(left: 10.w),
                style: TextStyle(
                  fontSize: 14.sp,
                  color: YxsColor.black,
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: 10.w, left: 10.w),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(top: 2.w),
                      child: Icon(
                        IconData(bean.mood, fontFamily: AssetsConstant.diyFont),
                        size: 13.sp,
                        color: Color(bean.color),
                      ),
                    ),
                    PaddingTextWidget(
                      bean.note,
                      style:
                          TextStyle(fontSize: 12.sp, color: YxsColor.black333),
                      padding: EdgeInsets.only(left: 10.w),
                    )
                  ],
                ),
              ),
            ],
          )
        ],
      ),
    );
  }

  //点击弹窗
  showClickDialog(BuildContext context, int year, int month, int day) {
    showDialog(
        context: context,
        builder: (ctx) {
          return HomeListDialog(year, month, day, (mood, color) {
            var bean = DateBean(
                month, year, day, color, Utils.colorDepth(color), mood);
            recordUtils.addData(bean);
            if (currentPageIndex != -1) {
              YearBean b = data[currentPageIndex];
              add(b.list, bean);
              data[currentPageIndex] = b;
              setState(() {});
              Navigator.of(ctx).pop();
            }
          }, () {}, () {});
        });
  }

  //同步数据
  void add(List<DateBean> list, DateBean data) {
    if (list.isNotEmpty) {
      var filter = list.where((it) =>
          it.month == data.month && it.year == data.year && it.day == data.day);
      if (filter.isEmpty) {
        list.add(data);
      } else {
        int indexOf = list.indexWhere((element) => element.day == data.day);
        if (indexOf > -1) list[indexOf] = data;
      }
    } else {
      list.add(data);
    }
    list.sort((b1, b2) => b1.day.compareTo(b2.day));
  }
}
